import React from 'react';
import FieldList from './fieldList';
import CommonListsIndex from '../../../components/CommonLists/index';
import FilterTool from '../../../components/FilterTool';
import services from '../../../services/api';
import { message } from 'antd';

class FieldIndex extends CommonListsIndex {
  constructor(props) {
    super(props);
    this.api = 'field';
    this.listsComponent = FieldList;
    this.queryParams = {};
    this.initQueryPanigation = {
      current_page: 1,
      page_size: 10,
    };
    this.state = {
      field_ids: [], // 已勾选的字段，复制要用
      applications: [],
      products: [],
      events: [],
      selectedRowKeys: [],
      app_id: '',
      event_id: '',
      filterItems: [],
      isChildInit: true,
      mapEventList: [], // 已经映射的事件
    };
    this.queryPanigation = {
      current_page: 1,
      page_size: 10,
    };
    this.queryTableParams = {};
    this.model_width = 600;
  }

  static getDerivedStateFromProps (props, state) {
    if (!props.mapping_relation || JSON.stringify(props.mapping_relation) === '{}') {
      return {
        selectedRowKeys: [],
      }
    }
    return null
  }

  componentDidMount() {
    this.getAppCodeList();
    this.getProductCodeList();
    if (this.props.actionType === 'child-update') {
      const { app_id, product_id, event_id } = this.props.childRecord;
      this.setState({ app_id, product_id, event_id });
      this.queryParams = { app_id, product_id, event_id };
      this.getEventCodeList(app_id, product_id);
      this.getProductCodeList(app_id, event_id);
      this.freshQueryList();
    }
    if (this.props.actionType === 'map') {
      this.getEventByInterface();
    }
  }

  // 获取当前接口下已映射的事件
  getEventByInterface = () => {
    const { third_list_config_id } = this.props.record;
    services.outerList.mapEvent({ third_list_config_id }).then((res) => {
      const { code, msg, data } = res;
      if (!code) {
        this.setState({ mapEventList: data });
      } else {
        message.error(msg);
      }
    });
  };

  updateFilterItems = () => {
    const { app_id, product_id, event_id } = this.state;
    this.setState({
      filterItems: [
        {
          type: 'Select',
          key: 'app_id',
          name: 'app_id',
          label: '渠道',
          defaultValue: app_id,
          span: 12,
          options: [
            ...this.state.applications.map((item) => {
              return {
                value: item.app_id,
                name: item.app_name,
              };
            }),
          ],
          onChange: this.onAppChangeSelect,
        },
        {
          type: 'Select',
          key: 'product_id',
          name: 'product_id',
          label: '产品',
          defaultValue: product_id,
          span: 12,
          options: [
            ...this.state.products.map((item) => {
              return {
                value: item.product_id,
                name: item.product_name,
              };
            }),
          ],
          onChange: this.onProductChangeSelect,
          allowClear: true,
        },
        {
          type: 'Select',
          key: 'event_id',
          name: 'event_id',
          label: '事件',
          defaultValue: event_id,
          span: 12,
          options: [
            ...this.state.events.map((item) => {
              return {
                value: item.event_id,
                name: item.event_name,
              };
            }),
          ],
          onChange: this.onEventChangeSelect,
        },
        {
          type: 'Search',
          key: 'name',
          name: 'name',
          defaultValue: '',
          span: 12,
          placeholder: '请输入字段名|字段Code进行搜索',
        },
      ],
    });
  };

  getAppCodeList = ({ product_id = -1, event_id = -1 } = {}) => {
    services.application.getAppCodeList({ product_id, event_id }).then((res) => {
      if (res.code === 0) {
        this.setState({
          applications: res.data,
        });
        this.updateFilterItems();
      }
    });
  };

  getProductCodeList = (app_id, event_id) => {
    services.product.getProductCodeList(event_id ? { app_id, event_id } : {}).then((res) => {
      if (res.code === 0) {
        // 当event_id存在，默认回写productId
        if (event_id) {
          const product_id = res.data.length === 1 ? res.data[0].product_id : undefined;
          this.setState(
            {
              product_id,
            },
            () => {
              const { app_id, product_id, event_id } = this.state;
              this.props.updateAppAndEvent(app_id, product_id, event_id, true);
              this.refs.filterTool.handleChange('product_id', product_id);
            }
          );
        }
        this.setState({
          products: res.data,
        });
        this.updateFilterItems();
      }
    });
  };

  getEventCodeList = (app_id, product_id) => {
    services.event.getEventCodeList({ app_id, product_id }).then((res) => {
      if (res.code === 0) {
        this.setState({
          events: res.data,
        });
        this.updateFilterItems();
        this.refs.filterTool.handleChange('event_id', '');
      }
    });
  };

  onChangePagination = (pageNumber, type = 'current_page') => {
    this.updatePanagaition &&
      this.updatePanagaition({
        [type]: pageNumber,
      });
    this.freshQueryList('pagination');
  };

  freshQueryList = (type) => {
    const { event_id } = this.queryParams;
    if (event_id) {
      if (this.props.actionType === 'map') {
        if (this.state.mapEventList.includes(event_id)) {
          this.clearList();
          return message.warning('该事件下已存在映射关系,请重新选择事件！');
        }
      }
      this.queryList({ ...this.queryParams, ...this.queryTableParams, ...this.queryPanigation }, type);
    } else {
      this.clearList();
    }
  };

  // 列表
  queryList = (params, type) => {
    services.outerList.fieldList(params).then((res) => {
      if (res.code === 0) {
        this.setState(
          {
            ...res.data,
          },
          () => {
            if (type === 'pagination' || type === 'name') return;
            const { app_id, product_id, event_id } = this.state;
            this.props.updateAppAndEvent(app_id, product_id, event_id);
          }
        );
      } else {
        message.error(res.msg);
      }
    });
  };

  refreshPanagaition = (params) => {
    this.queryPanigation = {
      ...this.queryPanigation,
      ...params,
    };
  };
  refreshFilter = (params, key) => {
    if (this.props.actionType === 'child-update') {
      const { name } = params;
      this.queryParams = { ...this.queryParams, name };
    } else {
      this.queryParams = params;
    }
    this.refreshPanagaition(this.initQueryPanigation);
    if (key === 'event_id' || key === 'name') {
      this.freshQueryList(key);
    }
  };

  refreshTableFilter = (params) => {
    this.queryTableParams = { ...this.queryTableParams, ...params };
    this.refreshPanagaition(this.initQueryPanigation);
    this.freshQueryList();
  };

  // onAppChangeSelect
  onAppChangeSelect = (_, e) => {
    this.setState(
      {
        event_id: '',
        app_id: e,
        selectedRowKeys: this.state.selectedRowKeys.splice(0),
      },
      () => {
        const { product_id, event_id } = this.state;
        this.getEventCodeList(e, product_id);
        this.props.updateAppAndEvent(e, product_id, event_id, true);
      }
    );
  };
  // onProductChangeSelect
  onProductChangeSelect = (_, e) => {
    if (!e) this.getProductCodeList();
    this.setState(
      {
        event_id: '',
        product_id: e,
        selectedRowKeys: this.state.selectedRowKeys.splice(0),
      },
      () => {
        const { app_id, event_id } = this.state;
        this.getEventCodeList(app_id, e);
        this.props.updateAppAndEvent(app_id, e, event_id, true);
      }
    );
  };
  // onEventChangeSelect
  onEventChangeSelect = (_, e) => {
    this.setState(
      {
        event_id: e,
        selectedRowKeys: this.state.selectedRowKeys.splice(0),
      },
      () => {
        const { app_id, product_id } = this.state;
        this.getProductCodeList(app_id, e);
        this.props.updateAppAndEvent(app_id, product_id, e, true);
      }
    );
  };

  updateSelectedRowKeys(field_id) {
    if (field_id) {
      this.state.selectedRowKeys[0] = field_id;
    } else {
      this.state.selectedRowKeys.splice(0);
    }
    this.setState({
      selectedRowKeys: this.state.selectedRowKeys,
    });
  }

  render() {
    const { mapping_relation, activeRow, disabled } = this.props;
    const ListsComponent = this.listsComponent;
    // 字段选择配置
    const rowSelection = {
      columnWidth: 30,
      onChange: (selectedRowKeys, selectedRows) => {
        if (selectedRowKeys.length > 0) {
          selectedRowKeys.splice(0, selectedRowKeys.length - 1);
        }
        if (selectedRows.length > 0) {
          selectedRows = selectedRows.filter((item) => item.field_id === selectedRowKeys[0]);
        }
        this.props.updateMap(selectedRows);
        this.setState({
          selectedRowKeys,
        });
      },
      getCheckboxProps: ({ field_code, field_id }) => {
        const mapping_relation_arr = (mapping_relation && activeRow && Object.values(mapping_relation)) || [];
        const active_id = activeRow ? activeRow.param_id : undefined;
        const current = (mapping_relation && mapping_relation[active_id]) || undefined;
        const isCurrent = (current && current.field_code === field_code) || false;

        return {
          disabled: !!(mapping_relation_arr.length > 0
            ? mapping_relation_arr.filter((it) => !!it).find((it) => it.field_code === field_code)
              ? isCurrent
                ? false
                : true
              : false
            : false),
          name: '' + field_id,
        };
      },
      hideDefaultSelections: true,
      selectedRowKeys: this.state.selectedRowKeys,
    };
    return (
      <div className='field-map'>
        <FilterTool
          ref='filterTool'
          data={this.state.filterItems}
          colNum={3}
          query={this.freshQueryList}
          refreshFilter={this.refreshFilter}
          isOnChange={true}
          isNotShowExpened={true}
          isSearchNotSpaceBetween={true}
          disabled={disabled}
        />
        <div style={{ marginTop: '10px' }} className='field-map-table'>
          <ListsComponent
            {...this.state}
            rowKey='field_id'
            applications={this.state.applications}
            edit={this.edit}
            queryList={this.freshQueryList}
            refreshTableFilter={this.refreshTableFilter}
            onChangePagination={this.onChangePagination}
            showDetail={this.showDetail}
            rowSelection={rowSelection}
            queryTableParams={this.queryTableParams}
            paginationSize={'small'}
            showSizeChanger={false}
          />
        </div>
      </div>
    );
  }
}

export default FieldIndex;
